import { ScriptExecutor } from './script-executor.js';

/**
 * 动作执行器模块
 * 处理规则动作的执行逻辑
 */
export class ActionExecutor {
  constructor() {
    this.scriptExecutor = new ScriptExecutor();
    this.supportedActionTypes = ['execute_script', 'script'];
  }

  /**
   * 执行规则动作
   */
  async executeRuleActions(rule, transaction) {
    console.log(`🎬 开始执行规则动作: ${rule.name}`);
    console.log(`📋 规则动作数量: ${rule.actions ? rule.actions.length : 0}`);
    
    if (!rule.actions || rule.actions.length === 0) {
      console.log(`⚠️ 规则 ${rule.name} 没有配置动作`);
      return;
    }

    const results = [];
    
    for (let i = 0; i < rule.actions.length; i++) {
      const action = rule.actions[i];
      console.log(`🎯 执行动作 ${i + 1}/${rule.actions.length}:`, {
        type: action.type,
        enabled: action.enabled,
        hasScript: !!action.script
      });
      
      // 如果enabled未定义，默认为启用；只有明确设置为false才禁用
      if (action.enabled === false) {
        console.log(`⏭️ 动作 ${i + 1} 已禁用，跳过`);
        results.push({ action: i + 1, status: 'skipped', reason: 'disabled' });
        continue;
      }

      try {
        await this.executeAction(action, rule, transaction);
        results.push({ action: i + 1, status: 'success' });
      } catch (error) {
        console.error(`❌ 执行规则动作失败 (${rule.name}):`, error);
        results.push({ action: i + 1, status: 'error', error: error.message });
      }
    }
    
    console.log(`✅ 规则动作执行完成: ${rule.name}`, results);
    return results;
  }

  /**
   * 执行单个动作
   */
  async executeAction(action, rule, transaction) {
    if (!this.supportedActionTypes.includes(action.type)) {
      console.warn(`⚠️ 未知的动作类型: ${action.type}`);
      return;
    }

    switch (action.type) {
      case 'execute_script':
      case 'script': // 支持前端发送的新格式
        await this.scriptExecutor.executeScript(action.script, rule, transaction);
        break;
        
      default:
        console.warn(`⚠️ 未实现的动作类型: ${action.type}`);
    }
  }

  /**
   * 验证动作配置
   */
  validateAction(action) {
    const errors = [];
    
    if (!action) {
      errors.push('动作不能为空');
      return errors;
    }
    
    if (!action.type) {
      errors.push('动作类型不能为空');
    } else if (!this.supportedActionTypes.includes(action.type)) {
      errors.push(`不支持的动作类型: ${action.type}`);
    }
    
    // 验证脚本动作
    if (['execute_script', 'script'].includes(action.type)) {
      if (!action.script) {
        errors.push('脚本动作必须包含脚本代码');
      } else {
        const scriptValidation = this.scriptExecutor.validateScript(action.script);
        if (scriptValidation.errors.length > 0) {
          errors.push(...scriptValidation.errors);
        }
      }
    }
    
    return errors;
  }

  /**
   * 验证规则的所有动作
   */
  validateRuleActions(rule) {
    const errors = [];
    
    if (!rule.actions || rule.actions.length === 0) {
      return errors; // 允许没有动作的规则
    }
    
    for (let i = 0; i < rule.actions.length; i++) {
      const action = rule.actions[i];
      const actionErrors = this.validateAction(action);
      
      if (actionErrors.length > 0) {
        errors.push(`动作 ${i + 1}: ${actionErrors.join(', ')}`);
      }
    }
    
    return errors;
  }

  /**
   * 获取支持的动作类型
   */
  getSupportedActionTypes() {
    return [...this.supportedActionTypes];
  }

  /**
   * 设置脚本执行超时
   */
  setScriptTimeout(timeout) {
    this.scriptExecutor.setTimeout(timeout);
  }

  /**
   * 获取脚本执行器
   */
  getScriptExecutor() {
    return this.scriptExecutor;
  }
} 